package tq.com.tqstudent.ui.activity.classes;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.LogUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import butterknife.BindView;
import tq.com.tqstudent.App;
import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.adapter.common.CommonAdapter;
import tq.com.tqstudent.adapter.common.ViewHolder;
import tq.com.tqstudent.bean.BaseBean;
import tq.com.tqstudent.bean.ChatBean;
import tq.com.tqstudent.bean.CommentBean;
import tq.com.tqstudent.bean.MalistBean;
import tq.com.tqstudent.bean.TeacherBean;
import tq.com.tqstudent.bean.event.ChatEvent;
import tq.com.tqstudent.net.ok.DialogCallback;
import tq.com.tqstudent.net.ok.StringCallback;
import tq.com.tqstudent.utils.VarietyUtil;

/**
 * @Author rames
 * @date 2019/3/6 14:14
 */
public class QuestionListActivity extends BaseActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty_layout)
    LinearLayout emptyLayout;
    private CommonAdapter adapter;
    private int index;
    private int pageNO = 1;

    public static void show(Activity activity, int id){
        Intent intent = new Intent(activity, QuestionListActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("index", id);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected void getExtras(Bundle extras) {
        this.index = extras.getInt("index");
    }

    @Override
    public int initLayout() {
        return R.layout.activity_recyclerview;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        setTitle("提问");

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CommonAdapter<MalistBean>(this, R.layout.item_question_list, new ArrayList()) {
            @Override
            protected void convert(ViewHolder holder, MalistBean bean, int position) {
                ArrayList<CommentBean> comments = bean.comment;
                if(null != comments && comments.size() > 0) {
                    CommentBean comment = comments.get(0);
                    LogUtil.e("position:"+position+" | comment: type="+comment.content_type+" | content: "+comment.content);
                    holder.setText(R.id.content_tv, getTypeContent(comment.content_type, comment.content));
                    holder.setText(R.id.name_tv, comment.author.name);
                    holder.setVisible(R.id.head_iv, true);
                    Glide.with(QuestionListActivity.this).load(VarietyUtil.getHeadImgUri(comment.author.pic)).apply(VarietyUtil.getGlideHeadOptions()).into((ImageView) holder.getView(R.id.head_iv));
                } else {
                    holder.setText(R.id.content_tv, "");
                    holder.setText(R.id.name_tv, "");
                    holder.setVisible(R.id.head_iv, false);
                }
                holder.setText(R.id.index_tv, (bean.title)+"题");
            }
        };
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener((view, holder, position) -> {
            MalistBean bean = (MalistBean) adapter.getDatas().get(position);
//            ArrayList<CommentBean> comments = bean.comment;
            setReadPoint(bean.author.id, true);
            ChatActivity.show(QuestionListActivity.this, true, (bean.title)+"题", 0, bean.id, position);
        });

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNO++;
                getData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNO = 1;
                getData();
            }
        });
    }

    private String getTypeContent(int type, String content){
        String ct = content;
        if(type == ChatBean.CONTENT_TYPE_TEXT){
            return ct;
        } else if(type == ChatBean.CONTENT_TYPE_IMAGE){
            return "[图片]";
        } else {
            return "[视频]";
        }
    }

    @Subscribe
    public void onChatBackEvent(ChatEvent event){
        refreshLayout.autoRefresh();
        /*ArrayList<MalistBean> list = (ArrayList<MalistBean>) adapter.getDatas();
        if(list.size() < 1 || list.size() < event.index) return;

        MalistBean bean = list.get(event.index);
        if(event != null && null != bean){
            CommentBean comment = null;
            if(null!=bean.comment && bean.comment.size()>0){
                comment = bean.comment.get(0);
                comment.author.name = event.bean.username;
                comment.author.pic = event.bean.icon;
            } else {
                comment = new CommentBean();
                TeacherBean teacher = new TeacherBean();
                teacher.name = event.bean.username;
                teacher.pic = event.bean.icon;
                comment.author = teacher;
            }

            comment.content = getTypeContent(event.bean.contentType, event.bean.message);
            bean.comment.clear();
            bean.comment.add(comment);
            adapter.notifyDataSetChanged();
        }*/
    }

    @Override
    public void initData() {
        getData();
    }

    private void getData() {
        String uri = "api/clz/malist/"+index+"/"+ (Constants.PAGE_SIZE*2)+"/"+pageNO;
        OkGo.<BaseBean<ArrayList<MalistBean>>>get(App.getHttpUrl(uri))
                .tag(this)
                .execute(new DialogCallback<ArrayList<MalistBean>>(QuestionListActivity.this) {
                    @Override
                    public void handleSuccess(ArrayList<MalistBean> data) {
                        // 这是加载更多
                        if(refreshLayout.getState() == RefreshState.Loading){
                            adapter.addData(data);
                            refreshLayout.finishLoadMore();
                            if(data.size() < Constants.PAGE_SIZE){
                                refreshLayout.setEnableLoadMore(false);
                            }

                            // 这是下拉刷新
                        } else {
                            adapter.getDatas().clear();
                            adapter.setData(data);
                            refreshLayout.finishRefresh();
                            refreshLayout.setEnableLoadMore(true);
                        }

                        emptyLayout.setVisibility(recyclerView.getAdapter().getItemCount() > 0 ? View.GONE : View.VISIBLE);
                    }

                    @Override
                    public void handleFail(BaseBean body) {
                        super.handleFail(body);
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                    }
                });
    }

    /**
     * 设置小红点的已读
     * @param targetID
     * @param isGroup 目标类型： 0 表示是目标是普通用户， 1 表示目标是群组
     */
    private void setReadPoint(int targetID, boolean isGroup){
        String uri = "api/im/setread";
        String json = "{\"target_id\""+":"+targetID+",\"score\""+":"+(isGroup?1:0)+"}";
        OkGo.<String>post(App.getHttpUrl(uri))
                .tag(this)
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });

    }
}
